package web.converters;

import java.util.List;

import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import ejb.entities.User;
import ejb.facade.UserFacade;
import javax.ejb.EJB;

@RequestScoped
@Named
public class UserConverter implements Converter {

	@EJB
	private UserFacade userFacade;

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,  String value) {
		List<User> lc = userFacade.findAll();
		if (value == null || "".equals(value))
			return null;
		if (lc == null)
			return null;
		
		for (User s : lc) {
			//if (s.getName().toLowerCase().contains(value.toLowerCase()))
			if (s.getUsername().equals(value))
				return s;
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value != null) {
			if ((value instanceof User)) {
				return String.valueOf(((User) value).getUsername());
			} else
				return value.toString();
		} else
			return null;
	}
}
